package com.yanqu.road.server.cmd.vehicle;

import com.yanqu.road.entity.player.UserVehicle;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.VehiclePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.vehicle.VehicleProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.vehicle.VehicleModule;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

import java.util.Map;

@Cmd(code = Protocol.S_VEHICLE_UPGRADE, desc = "座骑升级")
public class VehicleUpgradeCmd extends AbstractCommand {

	String vehicleUid;
	int times = 1;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		VehicleProto.VehicleUpgradeReqMsg reqMsg = VehicleProto.VehicleUpgradeReqMsg.parseFrom(packet.getBytes());
		vehicleUid = reqMsg.getVehicleUid();
		if(reqMsg.hasTimes() && reqMsg.getTimes() > 1){
			times = reqMsg.getTimes();
		}
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		if(times > 1){
			String[] split = GameConfig.VEHICLES_TEN_UPGRADE_LIMIT_PARAM.split("\\|");
			int needNum = Integer.parseInt(split[0]);
			int needLv = Integer.parseInt(split[1]);
			Map<String, UserVehicle> userVehicleMap = player.getModule(VehicleModule.class).getUserVehicleMap();
			int num = 0;
			for (Map.Entry<String, UserVehicle> vehicleEntry : userVehicleMap.entrySet()) {
				UserVehicle userVehicle = vehicleEntry.getValue();
				if (userVehicle.getLevel() >= needLv) {
					num++;
				}
			}
			if (num < needNum) {
				ret = GameErrorCode.E_VEHICLE_LEVEL_NO_ENOUGH;
				return;
			}
		}
		ret = player.getModule(VehicleModule.class).vehicleUpgrade(vehicleUid, times);
	}

	@Override
	public void sendData(GamePlayer player) {
		VehicleProto.VehicleUpgradeRespMsg.Builder respMsg = VehicleProto.VehicleUpgradeRespMsg.newBuilder();
		respMsg.setRet(ret);
		if(0 == ret){
			UserVehicle userVehicle = player.getModule(VehicleModule.class).getUserVehicle(vehicleUid);
			VehicleProto.VehicleTempMsg.Builder vehicleMsg = VehiclePb.parseVehicleTempMsg(userVehicle);
			if(null != vehicleMsg){
				respMsg.setVehicle(vehicleMsg);
			}
		}
		player.sendPacket(Protocol.U_VEHICLE_UPGRADE, respMsg);
	}
}
